const utils = require('../utils')
const db = require('./index')

exports.add = async function (params) {
  const {detail, title} = params
  const sql = `insert into {{name}}(id,title,detail,created_at,updated_at) VALUES (0,?,?,?,?);`
  const list = await db(sql, [title, detail, new Date(), new Date()])
  return list
}

exports.remove = async function (id) {
  const sql = `delete from {{name}} where id=?;`
  const data = await db(sql, [id])
  return data
}

exports.update = async function (params) {
  const sql = `update {{name}} set title=?, detail=?, updated_at=?, status=? where id = ?`
  const { id, title, detail, status } = params
  const data = await db(sql, [title, detail, new Date(), status, id])
  return data
}

exports.list = async function () {
  {{!-- const sqls = [
    `SELECT * FROM {{name}} ORDER BY updated_at DESC;`,
    `SELECT COUNT(*) as total FROM {{name}};`
  ]
  const datas = await Promise
    .all(sqls.map(async sql => await db(sql)))

  datas[0].forEach(data => {
    data.updated_at = utils.formatDate(data.updated_at)
    data.created_at = utils.formatDate(data.created_at)
  })

  const data = {
    data: datas[0],
    total: datas[1][0].total
  } --}}
  
  const sql = `SELECT * FROM {{name}} ORDER BY updated_at DESC;`
  const data = await db(sql)
  data.forEach(data => {
    data.updated_at = utils.formatDate(data.updated_at)
    data.created_at = utils.formatDate(data.created_at)
  })

  return data
}

exports.detail = async function (id) {
  const sql = `select * from {{name}} where id = ${id}`
  let data = await db(sql)
  if (data && data.length) {
    const _data = data[0]
    _data.updated_at = utils.formatDate(_data.updated_at)
    _data.created_at = utils.formatDate(_data.created_at)
    data = _data
  } else  {
    data = []
  }
}